package org.bluedream.core.module.sys.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.commons.collections.map.HashedMap;
import org.bluedream.comm.base.BaseEntity;
import org.bluedream.comm.utils.EmptyUtil;
import org.bluedream.comm.utils.RestResult;
import org.bluedream.comm.utils.StringUtils;
import org.bluedream.core.module.base.OrgBaseServiceImpl;
import org.bluedream.core.module.sys.dao.StoreDao;
import org.bluedream.core.module.sys.entity.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName StoreService
 * @Description TODO
 * @Author foxsand
 * @Data 2021-11-23 13:47
 * @Version
 */
@Service
@DS("master")
@Transactional(
        readOnly = true
)
public class StoreService extends OrgBaseServiceImpl<StoreDao, Store> implements IService<Store> {
    private static final Logger logger = LoggerFactory.getLogger(StoreService.class);

    @Override
    public Store getById(Serializable id) {
        if (EmptyUtil.isEmpty(id)){
            return new Store();
        }
        return super.getById(id);
    }

    public IPage<Store> findPage(Store entity, String... args) {
        Map<String , Object> search = new HashedMap();
        if (EmptyUtil.isNoEmpty(entity.getCode())
                || EmptyUtil.isNoEmpty(entity.getName())
                || EmptyUtil.isNoEmpty(entity.getOrgCode())
        ){
            if (EmptyUtil.isNoEmpty(entity.getCode())){
                search.put("code" , entity.getCode());
            }
            if (EmptyUtil.isNoEmpty(entity.getName())){
                search.put("name" , entity.getName());
            }
            if (EmptyUtil.isNoEmpty(entity.getOrgCode())){
                search.put("ORG_CODE;eq" , entity.getOrgCode());
            }
        }
        return super.findPage(entity , true , search , args);
    }

    @Transactional(
            readOnly = false,
            rollbackFor = Exception.class
    )
    public RestResult saveEntity(Store entity){
        try {
            super.save(entity);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            //todo:@Transactional和try catch捕获异常会让注解失效
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RestResult.error("数据保存失败:" + e.getMessage());
        }
        return RestResult.ok();
    }

    public List<Map<String , Object>> treeData(String excludeCode , String isShowCode){
        try {
            List<Map<String , Object>> mapList = new ArrayList<>();
            QueryWrapper<Store> queryWrapper = new QueryWrapper();
            queryWrapper.orderByAsc("code");
            List<Store> list = super.list(queryWrapper);
            for (Store c1:list
            ) {
                if (!BaseEntity.STATUS_NORMAL.equals(c1.getStatus())){
                    continue;
                }
                if (EmptyUtil.isNoEmpty(excludeCode)){
                    if (c1.getId().equals(excludeCode)){
                        continue;
                    }
                }
                Map<String , Object> map = new HashMap<>();
                String id = c1.getId();

                map.put("id" , id);
                map.put("pId" , "0");
                map.put("code" , c1.getCode());
                map.put("name" , StringUtils.getTreeNodeName(isShowCode , c1.getCode() , c1.getName()));
                map.put("isTreeLeaf" , true);
                map.put("isParent" , false);
                mapList.add(map);
            }
            return mapList;
        }catch (Exception e1){
            e1.printStackTrace();
        }
        return null;
    }
}
